/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 14:44:46
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.bp.bean.BpDeviceFacilityCollectionBean;
import com.joysuch.wwyt.bp.bean.BpMainMaterialDetailBean;
import com.joysuch.wwyt.bp.bean.BpMainMaterialEditBean;
import com.joysuch.wwyt.bp.bean.BpMainMaterialListBean;
import com.joysuch.wwyt.bp.bean.BpMainMaterialListBean.Search;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityCollection;
import com.joysuch.wwyt.bp.entity.BpMainMaterial;
import com.joysuch.wwyt.bp.entity.dsl.QBpMainMaterial;
import com.joysuch.wwyt.bp.enums.ProductTypes;
import com.joysuch.wwyt.bp.enums.SustanceForms;
import com.joysuch.wwyt.bp.repository.BpDeviceFacilityCollectionDao;
import com.joysuch.wwyt.bp.repository.BpMainMaterialDao;
import com.joysuch.wwyt.bp.repository.BpManufacturingTechDao;
import com.joysuch.wwyt.bp.service.BpMainMaterialService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.repository.MhMajorHazardDao;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class BpMainMaterialServiceImpl implements BpMainMaterialService {

    @Autowired
    private BpMainMaterialDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BpManufacturingTechDao bpManufacturingTechDao;
    @Autowired
    private MhMajorHazardDao mhMajorHazardDao;
    @Autowired
    private BpDeviceFacilityCollectionDao bpDeviceFacilityCollectionDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private BaseTypeGroupItemDao typeGroupItemDao;

    @Override
    public BpMainMaterial add(BpMainMaterialEditBean entity) throws Exception {
        BpMainMaterial content = new BpMainMaterial();
        // 类型
        content.setType(entity.getType());
        // 编号
        if (entity.getCode() != null) {
            Assert.isTrue(dao.countOfTypeAndCode(entity.getType(), entity.getCode()) == 0,
                    String.format("编号%s已经存在", entity.getCode()));
            content.setCode(entity.getCode());
        } else {
            if (ProductTypes.PRODUCT_MATIRIAL.getName().equals(entity.getType())) {
                content.setCode(bizCodeGeneratorFacade.shengChanYuanLiao());
            } else if (ProductTypes.MIDDLE_PRODUCT.getName().equals(entity.getType())) {
                content.setCode(bizCodeGeneratorFacade.zhongJianChanPin());
            } else if (ProductTypes.FINAL_PRODUCT.getName().equals(entity.getType())) {
                content.setCode(bizCodeGeneratorFacade.zuiZhongChanPin());
            }
        }
        // 品名
        content.setChemName(entity.getChemName());
        // CAS号
        content.setChemCas(entity.getChemCas());
        // 危化品目录序号
        content.setChemCategory(entity.getChemCategory());
        // 危化品ID
        content.setChemId(entity.getChemProductId());
        // 危险性类别
        content.setChemDangerType(entity.getChemDangerType());
        // 物质形态
        content.setSustanceFormId(entity.getSustanceFormId());

        if (entity.getYearly() != null) {
            String[] split = entity.getYearly();
            // 年消耗量
            if (split[0] != null && !"".equals(split[0])) {
                content.setYearlyCost(split[0]);
            }
            // 年消耗量计量单位
            if (split[1] != null && !"".equals(split[1])) {
                content.setYearlyCostUnit(split[1]);
            }
        }

        if (entity.getMax() != null) {
            String[] split = entity.getMax();
            // 最大储存量
            if (split[0] != null && !"".equals(split[0])) {
                content.setMaxStorage(split[0]);
            }
            // 最大储存量计量单位
            if (split[1] != null && !"".equals(split[1])) {
                content.setMaxStorageUnit(split[1]);
            }
        }

        // 储存场所ID（从collection中选）
        content.setStorePlaceId(entity.getStorePlaceId());
        // 是否属于高危存储设施
        content.setIsDangerousStorePlace(entity.getIsDangerousStorePlace());
        // 重大危险源ID
        content.setMajorHazardId(entity.getMajorHazardId());
        // 危险化学品重大危险源等级
        content.setMajorHazardRiskLevel(entity.getMajorHazardRiskLevel());
        // 工艺流程ID
        content.setManufatureTechId(entity.getManufatureTechId());
        // 是否属于重点监管危险化工工艺高危工艺
        content.setIsMainRegulatoryHchTech(entity.getIsMainRegulatoryHchTech());
        // 重点监管危险化工工艺
        content.setMainRegulatoryTech(entity.getMainRegulatoryTech());
        // 是否高危化学品
        content.setIsDangerousChem(entity.getIsDangerousChem());
        // 是否剧毒化学品
        content.setIsToxicChem(entity.getIsToxicChem());
        // 是否重点监管危险化学品
        content.setIsMainRegulatoryHch(entity.getIsMainRegulatoryHch());
        // 安全措施
        content.setSafetyMethod(entity.getSafetyMethod());
        // 应急处置措施
        content.setEmergencyMethod(entity.getEmergencyMethod());
        // 是否易制毒
        content.setIsEasyMakeDrug(entity.getIsEasyMakeDrug());
        // 是否易制爆
        content.setIsEasyExplode(entity.getIsEasyExplode());

        // 存储装置
        content.setStorageDevice(entity.getStorageDevice());
        // 存储方式
        content.setStorageType(entity.getStorageType());
        // 实际储量
        if (entity.getActual() != null) {
            String[] split = entity.getActual();
            if (split[0] != null && !"".equals(split[0])) {
                content.setActualStorge(split[0]);
            }
            if (split[1] != null && !"".equals(split[1])) {
                content.setActualStorgeUnit(split[1]);
            }
        }
        if (entity.getProduction() != null) {
            String[] split = entity.getProduction();
            // 年生产量
            if (split[0] != null && !"".equals(split[0])) {
                content.setYearProduction(split[0]);
            }
            // 年生产量单位
            if (split[1] != null && !"".equals(split[1])) {
                content.setYearProductionUnit(split[1]);
            }
        }
        //是否特别管控危险化学品
        content.setIsSpecialUnderControlChem(entity.getIsSpecialUnderControlChem());
        //是否为危化品
        content.setIsHazardousChemicals(entity.getIsHazardousChemicals());
        return dao.save(content);
    }

    @Override
    public void update(BpMainMaterialEditBean entity) throws Exception {
        BpMainMaterial content = dao.findById(entity.getId()).get();
        // 类型
        content.setType(entity.getType());
        // 编号
        Assert.notNull(entity.getCode(), "编号不能为空");
        Assert.isTrue(dao.countOfTypeAndCode(entity.getType(), entity.getCode(), entity.getId()) == 0,
                String.format("编号%s已经存在", entity.getCode()));
        content.setCode(entity.getCode());

        // 品名
        content.setChemName(entity.getChemName());
        // CAS号
        content.setChemCas(entity.getChemCas());
        // 危化品目录序号
        content.setChemCategory(entity.getChemCategory());
        // 危化品ID
        content.setChemId(entity.getChemProductId());
        // 危险性类别
        content.setChemDangerType(entity.getChemDangerType());
        // 物质形态
        content.setSustanceFormId(entity.getSustanceFormId());

        if (entity.getYearly() != null) {
            String[] split = entity.getYearly();
            // 年消耗量
            if (split[0] != null && !"".equals(split[0])) {
                content.setYearlyCost(split[0]);
            }

            // 年消耗量计量单位
            if (split[1] != null && !"".equals(split[1])) {
                content.setYearlyCostUnit(split[1]);
            }

        }
        if (entity.getMax() != null) {
            String[] split = entity.getMax();
            // 最大储存量
            if (split[0] != null && !"".equals(split[0])) {
                content.setMaxStorage(split[0]);
            }
            // 最大储存量计量单位
            if (split[1] != null && !"".equals(split[1])) {
                content.setMaxStorageUnit(split[1]);
            }
        }
        // 储存场所ID（从collection中选）
        content.setStorePlaceId(entity.getStorePlaceId());
        // 是否属于高危存储设施
        content.setIsDangerousStorePlace(entity.getIsDangerousStorePlace());
        // 重大危险源ID
        content.setMajorHazardId(entity.getMajorHazardId());

        // 危险化学品重大危险源等级
        content.setMajorHazardRiskLevel(entity.getMajorHazardRiskLevel());
        // 工艺流程ID
        content.setManufatureTechId(entity.getManufatureTechId());
        // 是否属于重点监管危险化工工艺高危工艺
        content.setIsMainRegulatoryHchTech(entity.getIsMainRegulatoryHchTech());
        // 重点监管危险化工工艺
        content.setMainRegulatoryTech(entity.getMainRegulatoryTech());
        // 是否高危化学品
        content.setIsDangerousChem(entity.getIsDangerousChem());
        // 是否剧毒化学品
        content.setIsToxicChem(entity.getIsToxicChem());
        // 是否重点监管危险化学品
        content.setIsMainRegulatoryHch(entity.getIsMainRegulatoryHch());
        // 安全措施
        content.setSafetyMethod(entity.getSafetyMethod());
        // 应急处置措施
        content.setEmergencyMethod(entity.getEmergencyMethod());
        // 是否易制毒
        content.setIsEasyMakeDrug(entity.getIsEasyMakeDrug());
        // 是否易制爆8
        content.setIsEasyExplode(entity.getIsEasyExplode());

        // 存储装置
        content.setStorageDevice(entity.getStorageDevice());
        // 存储方式
        content.setStorageType(entity.getStorageType());
        // 实际储量
        if (entity.getActual() != null) {
            String[] split = entity.getActual();
            // 最大储存量
            if (split[0] != null && !"".equals(split[0])) {
                content.setActualStorge(split[0]);
            }
            // 最大储存量计量单位
            if (split[1] != null && !"".equals(split[1])) {
                content.setActualStorgeUnit(split[1]);
            }
        }
        // 年生产力
        if (entity.getProduction() != null) {
            String[] split = entity.getProduction();
            if (split[0] != null && !"".equals(split[0])) {
                content.setYearProduction(split[0]);
            }
            if (split[1] != null && !"".equals(split[1])) {
                content.setYearProductionUnit(split[1]);
            }
        }
        //是否特别管控危险化学品
        content.setIsSpecialUnderControlChem(entity.getIsSpecialUnderControlChem());
        //是否为危化品
        content.setIsHazardousChemicals(entity.getIsHazardousChemicals());
        dao.save(content);
    }

    @Override
    public Page<BpMainMaterialListBean> findByPage(Pageable page, Search condition) {
        QBpMainMaterial bpMainMaterial = QBpMainMaterial.bpMainMaterial;
        Predicate predicate = bpMainMaterial.isNotNull();
        predicate = condition.getChemName() == null ? predicate
                : ExpressionUtils.and(predicate,
                ExpressionUtils.or(bpMainMaterial.chemName.like("%" + condition.getChemName() + "%"),
                        bpMainMaterial.code.like("%" + condition.getChemName() + "%")));
        predicate = condition.getType() == null ? predicate
                : ExpressionUtils.and(predicate, bpMainMaterial.type.like(condition.getType()));
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpMainMaterial> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data, new PageDataConvert<BpMainMaterialListBean, BpMainMaterial>() {

            @Override
            public BpMainMaterialListBean convert(BpMainMaterial f) {
                BpMainMaterialListBean bean = new BpMainMaterialListBean();
                // ID
                bean.setId(f.getId());
                // 类型
                bean.setType(f.getType());
                // 编号
                bean.setCode(f.getCode());
                // 品名
                bean.setChemName(f.getChemName());
                // CAS号
                bean.setChemCas(f.getChemCas());
                // 危化品目录序号
                bean.setChemCategory(f.getChemCategory());
                // 危化品ID
                bean.setChemId(f.getChemId());
                // 危险性类别
                bean.setChemDangerType(f.getChemDangerType());
                // 物质形态
                bean.setSustanceFormId(f.getSustanceFormId());
                /*
                 * //年消耗量
                 * bean.setYearlyCost(f.getYearlyCost());
                 * //年消耗量计量单位
                 * bean.setYearlyCostUnit(f.getYearlyCostUnit());
                 */
                if (f.getYearlyCost() != null && f.getYearlyCostUnit() != null) {
                    bean.setYearly(new String[]{f.getYearlyCost() + f.getYearlyCostUnit()});
                }

                /*
                 * //最大储存量
                 * bean.setMaxStorage(f.getMaxStorage());
                 * //最大储存量计量单位
                 * bean.setMaxStorageUnit(f.getMaxStorageUnit());
                 */
                if (f.getMaxStorage() != null && f.getMaxStorageUnit() != null) {
                    bean.setMax(new String[]{f.getMaxStorage() + f.getMaxStorageUnit()});
                }

                // 储存场所ID（从collection中选）
                bean.setStorePlaceId(f.getStorePlaceId());
                if (bean.getStorePlaceId() != null) {
                    riskDistrictDao.findById(bean.getStorePlaceId()).ifPresent((place) -> {
                        bean.setStorePlaceName(place.getName());
                    });
                }
                // 是否属于高危存储设施
                bean.setIsDangerousStorePlace(f.getIsDangerousStorePlace());
                // 重大危险源ID
                bean.setMajorHazardId(f.getMajorHazardId());
                // 危险化学品重大危险源等级
                bean.setMajorHazardRiskLevel(f.getMajorHazardRiskLevel());
                // 工艺流程ID
                bean.setManufatureTechId(f.getManufatureTechId());
                // 是否属于重点监管危险化工工艺高危工艺
                bean.setIsMainRegulatoryHchTech(f.getIsMainRegulatoryHchTech());
                // 重点监管危险化工工艺
                bean.setMainRegulatoryTech(f.getMainRegulatoryTech());
                // 是否高危化学品
                bean.setIsDangerousChem(f.getIsDangerousChem());
                // 是否剧毒化学品
                bean.setIsToxicChem(f.getIsToxicChem());
                // 是否重点监管危险化学品
                bean.setIsMainRegulatoryHch(f.getIsMainRegulatoryHch());
                // 安全措施
                bean.setSafetyMethod(f.getSafetyMethod());
                // 应急处置措施
                bean.setEmergencyMethod(f.getEmergencyMethod());
                // 是否易制毒
                bean.setIsEasyMakeDrug(f.getIsEasyMakeDrug());
                // 是否易制爆
                bean.setIsEasyExplode(f.getIsEasyExplode());

                //存储装置
                bean.setStorageDevice(f.getStorageDevice());
                //存储方式
                bean.setStorageType(f.getStorageType());
                //实际储量
                if (f.getActualStorge() != null && f.getActualStorgeUnit() != null) {
                    bean.setActual(new String[]{f.getActualStorge() + f.getActualStorgeUnit()});
                }
                //年生产力
                if (f.getYearProduction() != null && f.getYearProductionUnit() != null) {
                    bean.setProduction(new String[]{f.getYearProduction() + f.getYearProductionUnit()});
                }
                //是否为特别管控危险化学品
                bean.setIsSpecialUnderControlChem(f.getIsSpecialUnderControlChem());
                //是否为危化品
                bean.setIsHazardousChemicals(f.getIsHazardousChemicals());
                return bean;
            }

        });
    }

    private Predicate prepareListSearchCondition(Search condition) {
        return null;
    }

    @Override
    public void delete(Long id) {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        dao.deleteById(id);
    }

    @Override
    public BpMainMaterial findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public List<BpDeviceFacilityCollectionBean> getCollection() {
        ArrayList<BpDeviceFacilityCollectionBean> list = new ArrayList<>();
        List<BpDeviceFacilityCollection> all = bpDeviceFacilityCollectionDao.findAll();
        for (BpDeviceFacilityCollection bpDeviceFacilityCollection : all) {
            if (bpDeviceFacilityCollection.getDeviceTypeId() == 6
                    || bpDeviceFacilityCollection.getDeviceTypeId() == 4) {
                BpDeviceFacilityCollectionBean b = new BpDeviceFacilityCollectionBean();
                b.setCode(bpDeviceFacilityCollection.getCode());
                b.setDeviceId(bpDeviceFacilityCollection.getDeviceId());
                b.setDeviceTypeId(bpDeviceFacilityCollection.getDeviceTypeId());
                b.setDeviceTypeName(bpDeviceFacilityCollection.getDeviceTypeName());
                b.setStorePlaceId(bpDeviceFacilityCollection.getId());
                b.setName(bpDeviceFacilityCollection.getName());
                list.add(b);
            }
        }
        return list;
    }

    @Override
    public BpMainMaterialDetailBean getById(Long id) {
        BpMainMaterial entity = findById(id);
        BpMainMaterialDetailBean bean = new BpMainMaterialDetailBean();
        // ID
        bean.setId(entity.getId());

        // 类型
        bean.setType(entity.getType());

        // 编号
        bean.setCode(entity.getCode());

        // 品名
        bean.setChemName(entity.getChemName());

        // CAS号
        bean.setChemCas(entity.getChemCas());

        // 危化品目录序号
        bean.setChemCategory(entity.getChemCategory());

        // 危化品ID
        bean.setChemId(entity.getChemId());

        // 危险性类别
        bean.setChemDangerType(entity.getChemDangerType());

        // 年消耗量和单位
        if (entity.getYearlyCost() != null && entity.getYearlyCostUnit() != null) {
            bean.setYearly(new String[]{entity.getYearlyCost() + "", entity.getYearlyCostUnit()});
        }

        // 最大储存量计量单位
        String maxStorage = "";
        String maxStorageUnit = "";
        if (entity.getMaxStorage() != null) {
            maxStorage = entity.getMaxStorage();
        }
        if (entity.getMaxStorageUnit() != null) {
            maxStorageUnit = entity.getMaxStorageUnit();
        }
        bean.setMax(new String[]{maxStorage + "", maxStorageUnit});


        // 储存场所ID（从collection中选）
        bean.setStorePlaceId(entity.getStorePlaceId());
        if (bean.getStorePlaceId() != null) {
            riskDistrictDao.findById(bean.getStorePlaceId()).ifPresent((place) -> {
                bean.setStorePlaceName(place.getName());
            });
        }

        // 是否属于高危存储设施
        bean.setIsDangerousStorePlace(entity.getIsDangerousStorePlace());
        bean.setIsDangerousStorePlaceName(
                BizUtils.translateYesNoToChineseForNotNull(entity.getIsDangerousStorePlace()));
        // 重大危险源ID
        bean.setMajorHazardId(entity.getMajorHazardId());
        if (entity.getMajorHazardId() != null) {
            mhMajorHazardDao.findById(entity.getMajorHazardId())
                    .ifPresent((one) -> bean.setMajorHazardName(one.getName()));
        }

        // 危险化学品重大危险源等级
        bean.setMajorHazardRiskLevel(entity.getMajorHazardRiskLevel());
        bean.setMajorHazardRiskLevelName(RiskLevels.findRiskLevelName(entity.getMajorHazardRiskLevel()));
        // 工艺流程ID
        bean.setManufatureTechId(entity.getManufatureTechId());
        if (entity.getManufatureTechId() != null) {
            bpManufacturingTechDao.findById(entity.getManufatureTechId())
                    .ifPresent((one1) -> bean.setManufatureTechName(one1.getName()));
        }

        // 是否属于重点监管危险化工工艺高危工艺
        bean.setIsMainRegulatoryHchTech(entity.getIsMainRegulatoryHchTech());
        bean.setIsMainRegulatoryHchTechName(
                BizUtils.translateYesNoToChineseForNotNull(entity.getIsMainRegulatoryHchTech()));

        // 重点监管危险化工工艺
        bean.setMainRegulatoryTech(entity.getMainRegulatoryTech());

        // 是否高危化学品
        bean.setIsDangerousChem(entity.getIsDangerousChem());
        bean.setIsDangerousChemName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsDangerousChem()));

        // 是否剧毒化学品
        bean.setIsToxicChem(entity.getIsToxicChem());
        bean.setIsToxicChemName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsToxicChem()));

        // 是否重点监管危险化学品
        bean.setIsMainRegulatoryHch(entity.getIsMainRegulatoryHch());
        bean.setIsMainRegulatoryHchName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsMainRegulatoryHch()));

        // 安全措施
        bean.setSafetyMethod(entity.getSafetyMethod());

        // 应急处置措施
        bean.setEmergencyMethod(entity.getEmergencyMethod());

        // 是否易制毒
        bean.setIsEasyMakeDrug(entity.getIsEasyMakeDrug());
        bean.setIsEasyMakeDrugName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsEasyMakeDrug()));

        // 是否易制爆
        bean.setIsEasyExplode(entity.getIsEasyExplode());
        bean.setIsEasyExplodeName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsEasyExplode()));
        bean.setSustanceFormId(entity.getSustanceFormId());
        if (entity.getSustanceFormId() != null) {
            bean.setSustanceFormName(SustanceForms.findNameById(entity.getSustanceFormId().intValue()));
        }


        bean.setStorageDevice(entity.getStorageDevice());
        bean.setStorageType(entity.getStorageType());
        // 实际储存量计量单位
        String actualStorge = "";
        String actualStorgeUnit = "";
        if (entity.getActualStorge() != null) {
            actualStorge = entity.getActualStorge() + "";
        }
        if (entity.getActualStorgeUnit() != null) {
            actualStorgeUnit = entity.getActualStorgeUnit();
        }
        bean.setActual(new String[]{actualStorge + "", actualStorgeUnit});
        // 年生产力计量单位
        String yearProduction = "";
        String yearProductionUnit = "";
        if (entity.getYearProduction() != null) {
            yearProduction = entity.getYearProduction() + "";
        }
        if (entity.getYearProductionUnit() != null) {
            yearProductionUnit = entity.getYearProductionUnit();
        }
        bean.setProduction(new String[]{yearProduction + "", yearProductionUnit});
        bean.setIsSpecialUnderControlChem(entity.getIsSpecialUnderControlChem());
        bean.setIsSpecialUnderControlChemName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsSpecialUnderControlChem()));
        bean.setIsHazardousChemicals(entity.getIsHazardousChemicals());
        bean.setIsHazardousChemicalsName(BizUtils.translateYesNoToChineseForNotNull(entity.getIsHazardousChemicals()));
        return bean;
    }

}
